package de.backtomedieval.activities.gamemenu;

import java.util.ArrayList;

import de.backtomedieval.units.*;
import de.backtomedieval.activities.TopBar;
import de.backtomedieval.buildings.Barracks;
import de.backtomedieval.buildings.Siege_Manufacture;
import de.backtomedieval.R;
import de.backtomedieval.main.Game;
import de.backtomedieval.error.NotEnoughWaresException;
import de.backtomedieval.game.Helper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class UnitBuildMenu extends Activity {
	//TODO: cityinfo
	private Handler mHandler = new Handler();
	private UnitsToBuildAdapter m_unitsToBuildadapter;
	private ArrayList<UnitOrder> m_barrack_unitsToBuild;
	private AbstractUnit choosedUnit = null;
	private ArrayList<AbstractUnit> m_unitchoose;
	private UnitchooseAdapter m_unitchooseadapter;
	private ListView lv2;
	private Barracks barracks;
	private Siege_Manufacture manufacture;
	private EditText evBuildCount;
	private ListView lv1;
	private int refresh = Game.getRefreshrate();
	private TextView tv_unitinfo;
	private GridView grid_main;
	private TopBar topbar;
	
	@Override
	public void onCreate(Bundle savedInstanceState)	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.unitbuildmenu);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );

		
		tv_unitinfo = (TextView) findViewById(R.id.unitbuild_description);
		
		topbar = new TopBar(this);
		topbar.setTitle(Game.getGame().getcCity().getName() + ": "+ getString(R.string.units));
		

		lv1=(ListView)findViewById(R.id.ListViewUnitchoose);
		m_unitchoose = new ArrayList<AbstractUnit>();
		this.m_unitchooseadapter = new UnitchooseAdapter(this, R.layout.row, m_unitchoose);
		lv1.setAdapter(this.m_unitchooseadapter);
		ArrayList<AbstractUnit> u = AbstractUnit.getUnitList(Game.getGame().getPlayer().getTechnology());
		for (int i=0; i<u.size(); i++) {
			m_unitchooseadapter.add(u.get(i));
		}
		m_unitchooseadapter.notifyDataSetChanged();
		lv1.setTextFilterEnabled(true);
		lv1.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				onUnitchooseListChoose(position);
			}
		});	

		barracks = Game.getGame().getcCity().getBarrack();
		manufacture =Game.getGame().getcCity().getManufacture();
		lv2=(ListView)findViewById(R.id.ListViewBarrack);
		m_barrack_unitsToBuild = new ArrayList<UnitOrder>();
		this.m_unitsToBuildadapter = new UnitsToBuildAdapter(this, R.layout.listitem_unittobuild, m_barrack_unitsToBuild );
		lv2.setAdapter(this.m_unitsToBuildadapter);
		for (int i=0; i<barracks.getUnitsToBuild().size();i++){
			m_unitsToBuildadapter.add(barracks.getUnitsToBuild().get(i));
			m_unitsToBuildadapter.notifyDataSetChanged();
		}


		Button buttonBuildUnits = (Button) findViewById(R.id.ButtonBuildUnits);
		buttonBuildUnits.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				switchToUnitchooseList();

			}});

		evBuildCount = (EditText) findViewById(R.id.EditViewBuildCount);
		
		

		grid_main = (GridView)findViewById(R.id.GridViewMenu);
		grid_main.setAdapter(new ImageAdapter(this));
        grid_main.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	onUnitInfoMenuChoose(position);
            }
        });

	}

	protected void onUnitInfoMenuChoose(int position) {
		if (choosedUnit != null) {
			if (position==0) {
				onBuildUnit();
			}
		}
	}
	
	private void onBuildUnit() {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(evBuildCount.getWindowToken(), 0);
		if (choosedUnit.getBuildIn()==AbstractUnit.BUILD_IN_BARRACKS &&  !barracks.isBuilded()) {
			Game.showPopup(UnitBuildMenu.this,  getString(R.string.tobuild) + " " + choosedUnit.getName() + " " +  getString(R.string.barracksneeded));
			switchToUnitchooseList();
			return;
		}
		if (choosedUnit.getBuildIn()==AbstractUnit.BUILD_IN_MANUFRACTURE &&  !manufacture.isBuilded()) {
			Game.showPopup(UnitBuildMenu.this, getString(R.string.tobuild) + " " + choosedUnit.getName() + " " + getString(R.string.manufactureneeded)) ;
			switchToUnitchooseList();
			return;
		}
		if (evBuildCount.getText().equals("")) return;
		int count = Integer.parseInt(evBuildCount.getText().toString());
		
		int howmuch = Game.getGame().getcCity().howMuchUnitsCanWeAfford(choosedUnit);
		if (howmuch==0) {
			Game.showPopup(UnitBuildMenu.this, "Not enough wares to build "+  choosedUnit.getName() + ".") ;
		} else if (howmuch < count) {
			try {
				build(new UnitOrder(choosedUnit,howmuch));
				Game.showPopup(UnitBuildMenu.this, "Not enough wares for " + count + " " + choosedUnit.getName() + ". " + howmuch + " build.") ;
			} catch (NotEnoughWaresException e) {}
		} else {
			try {
				build(new UnitOrder(choosedUnit,count));
				
			} catch (NotEnoughWaresException e) {}
		}
		
		UnitBuildMenu.this.switchToBuildList();
	}


	protected void switchToUnitchooseList() {
		LinearLayout l2 =(LinearLayout)findViewById(R.id.Layoutunitbuildlist);
		l2.setVisibility(8);
		LinearLayout l1 =(LinearLayout)findViewById(R.id.Layoutunitbuildnewunit);
		l1.setVisibility(0);
		LinearLayout l3 =(LinearLayout)findViewById(R.id.LayoutUnitInfo);
		l3.setVisibility(8);
	}

	@Override
	public void onBackPressed() {
		LinearLayout l1 =(LinearLayout)findViewById(R.id.LayoutUnitInfo);
		LinearLayout l2 =(LinearLayout)findViewById(R.id.Layoutunitbuildnewunit);
		int vis1 = l1.getVisibility();
		int vis2 = l2.getVisibility();
		if (vis1 == 0) {
			this.switchToUnitchooseList();
		} else if (vis2 ==0){
			this.switchToBuildList();
		} else {	
			mHandler.removeCallbacks(mUnitsToBuildListTask);
			Intent changeToIntent = new Intent(this,Gamemenu.class);
			startActivity(changeToIntent);
			this.finish();
		}

		return;
	}
	
	private class CreateUnitInfoTask extends AsyncTask<Void, Void, String> {
	    /** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
		@Override
		protected String doInBackground(Void... params) {
			 return buildUnitInfo();
		}
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(String result) {
	    	Log.v("Update", "BuildUnitInfo");
	    	tv_unitinfo.setText(Html.fromHtml(result, imgGetter, null));
	    }
	}
	
	
	protected void onUnitchooseListChoose(int position) {
		if (position!=-1) {
			choosedUnit = m_unitchooseadapter.getItem(position);
			int howmuch = Game.getGame().getcCity().howMuchUnitsCanWeAfford(choosedUnit);
			if (howmuch==0) {
				howmuch=1;
			}
			this.evBuildCount.setText(""+howmuch);
			new CreateUnitInfoTask().execute();
			LinearLayout l1 =(LinearLayout)findViewById(R.id.Layoutunitbuildnewunit);
			l1.setVisibility(8);
			LinearLayout l2 =(LinearLayout)findViewById(R.id.LayoutUnitInfo);
			l2.setVisibility(0);
		}
	}

	private String buildUnitInfo() {
		return "<Big><b>" + choosedUnit.getName() + "</Big></b><br><br>"+
		getString(R.string.healthpoints) +": " + choosedUnit.getHealthpoints() + "<br>" + 
		getString(R.string.attack) + ": " + choosedUnit.getAttack() + " (" +  choosedUnit.getAttackMultiple() +  "x)<br>" + 
		getString(R.string.attackchance)+ ": " + choosedUnit.getAttackquality() + "%<br>" + 
		getString(R.string.defense) + ": " + choosedUnit.getDefense() + "<br>" + 
		getString(R.string.attacksinrounds)+ ": " + choosedUnit.getAttackroundString() + "<br>"+ 
		"<br>" + choosedUnit.getCosts().toString(1);
	}

	protected void switchToBuildList() {
		LinearLayout l2 =(LinearLayout)findViewById(R.id.Layoutunitbuildlist);
		l2.setVisibility(0);
		LinearLayout l1 =(LinearLayout)findViewById(R.id.Layoutunitbuildnewunit);
		l1.setVisibility(8);
		LinearLayout l3 =(LinearLayout)findViewById(R.id.LayoutUnitInfo);
		l3.setVisibility(8);
	}

	public void build(UnitOrder u) throws NotEnoughWaresException {
		Game.getGame().getcCity().buildUnits(u);
		m_unitsToBuildadapter.add(u);
		m_unitsToBuildadapter.notifyDataSetChanged();
	}

	public void refreshUnitsToBuildList() {
		for (int i=0; i<m_unitsToBuildadapter.getCount();i++) {
			if (m_unitsToBuildadapter.getItem(i).isOrderComplete()) {
				m_unitsToBuildadapter.remove(m_unitsToBuildadapter.getItem(i));
				i--;
				m_unitsToBuildadapter.notifyDataSetChanged();
			}
		}
		m_unitsToBuildadapter.notifyDataSetChanged();
	}


	private Runnable mUnitsToBuildListTask = new Runnable() {
		public void run() {
			Log.v("Update", "UnitMenu: Cityinfo");
			refreshUnitsToBuildList();
			topbar.refreshCityInfo();
			mHandler.postDelayed(this,refresh);
		}
	};



   ImageGetter imgGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
              //drawable = Drawable.createFromPath(source);  // Or fetch it from the URL
              Resources res = UnitBuildMenu.this.getResources();
              Drawable drawable = res.getDrawable(Helper.getImageFromString(source));
              // Important
              //drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
              drawable.setBounds(0, 0, drawable.getIntrinsicWidth()/3, drawable.getIntrinsicHeight()/3);
              return drawable;
        }
    };

	private class UnitsToBuildAdapter extends ArrayAdapter<UnitOrder> {

		private ArrayList<UnitOrder> items;

		public UnitsToBuildAdapter(Context context, int textViewResourceId, ArrayList<UnitOrder> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row, null);
			}
			UnitOrder o = items.get(position);
			AbstractUnit u = o.getUnit();
			if (o != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				ImageView icon=(ImageView)v.findViewById(R.id.icon);
				icon.setImageResource(u.getImage());
				if (tt != null) {
					tt.setText(u.getName());
				}
				if(bt != null){
					if (u.getBuildIn()==AbstractUnit.BUILD_IN_BARRACKS) {
						bt.setText(o.getBuildCountPercent() + " "  + getString(R.string.unitbuild_buildedbarracks) +".");
					} else if (u.getBuildIn()==AbstractUnit.BUILD_IN_MANUFRACTURE) {
						bt.setText(o.getBuildCountPercent() + " " + getString(R.string.unitbuild_buildedmanufacture) +".");
					}
				}
			}
			return v;
		}
	}


	private class UnitchooseAdapter extends ArrayAdapter<AbstractUnit> {

		private ArrayList<AbstractUnit> items;

		public UnitchooseAdapter(Context context, int textViewResourceId, ArrayList<AbstractUnit> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row, null);
			}
			AbstractUnit o = items.get(position);
			if (o != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				ImageView icon=(ImageView)v.findViewById(R.id.icon);
				icon.setImageResource(o.getImage());
				if (tt != null) {
					tt.setText(o.getName());
				}
				if(bt != null){
					bt.setText("");


				}
			}
			return v;
		}
	}
	
	public class ImageAdapter extends BaseAdapter{
		Context mContext;
		public static final int ACTIVITY_CREATE = 10;
		public ImageAdapter(Context c){
			mContext = c;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return 1;
		}


		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v;
			if(convertView==null){
				LayoutInflater li = getLayoutInflater();
				v = li.inflate(R.layout.gridiconlarge, null);
				TextView tv = (TextView)v.findViewById(R.id.icon_text);
				ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
				if (choosedUnit!=null) {
					if(position ==0) {
						tv.setText(R.string.unitbuild_build);
						iv.setImageResource(R.drawable.icon);
					}
				}

			}
			else{
				v = convertView;
			}
			return v;
		}
		
		
		
		public Object getItem(int position) {
			return null;
		}
		
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
	}
	
	
	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onPause() {
		super.onPause();
		mHandler.removeCallbacks(mUnitsToBuildListTask);
	}
	
	@Override
	public void onResume(){
	   super.onResume();
	   Game.setLastActivity(this);
		mHandler.removeCallbacks(mUnitsToBuildListTask);
		mHandler.postDelayed(mUnitsToBuildListTask, 100);
	}
	
}
